package com.fessc.develop.handler.processor.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fessc.develop.base.Result;
import com.fessc.develop.entity.comvo.PaymentCallBackVo;
import com.fessc.develop.model.enums.EnumJsonProperty;
import com.fessc.develop.model.enums.EnumServiceCode;
import com.fessc.develop.handler.processor.request.IBaseService;
import com.fessc.develop.utils.BusiUtil;
import com.fessc.develop.utils.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ComPaymentCallBackService implements IBaseService {

    @Resource
    private List<ICallBackProcessor> callBackProcessorList;

    private Map<String, ICallBackProcessor> callBackProcessorMap;

    @PostConstruct
    void init() {
        if (BusiUtil.isNotNull(callBackProcessorList)) {
            callBackProcessorMap = callBackProcessorList.stream().collect(Collectors.toMap(ICallBackProcessor::getOption, p->p, (v1, v2) -> v1));
        } else {
            callBackProcessorMap = new HashMap<>();
        }
    }

    @Override
    public String getServiceCode() {
        return EnumServiceCode.COM_BS0005.toString();
    }

    @Override
    public Result process(JSONObject request) {
        Result result;
        log.info("交易结果回调通知请求报文：" + request);
        PaymentCallBackVo bankCallBackVo = JSON.parseObject(request.getJSONObject(EnumJsonProperty.REQ_BODY.toString()).toJSONString(), PaymentCallBackVo.class);
        ICallBackProcessor callBackProcessor = callBackProcessorMap.get(bankCallBackVo.getOption());
        if (BusiUtil.isNull(callBackProcessor)) {
            throw ExceptionUtil.businessException("EE4012");
        }
        result = callBackProcessor.process(bankCallBackVo);
        return result;
    }
}
